package main

import (
	"fmt"
	"sync"
	"time"
)

var (
	myMap02 = make(map[int]int, 10)
	//lock 是一个全局的互斥锁
	// sync 是包：synchronize 同步
	//Mutex: 是互斥
	lock sync.Mutex
)

func test_02(n int) {
	res := 1
	for j := 1; j <= n; j++ {
		res += j
	}
	lock.Lock() //加锁
	myMap02[n] = res
	lock.Unlock() // 解锁
}

/**

  发生错误：fatal error: concurrent map writes
  查看资源竞争的情况： -race
  例如：
   go build -race channel_01_err.go
   ././channel_01

解除方案：
  1.全变量加锁


*/
func main() {
	for i := 1; i <= 200; i++ {
		go test_02(i)
	}

	//休眠10s
	time.Sleep(time.Second * 5)

	//for i,v := range myMap02 {
	//	fmt.Printf("map[%d]=%d \n",i,v)
	//}
	for i := 1; i <= 200; i++ {
		fmt.Printf("map[%d]=%d \n", i, myMap02[i])
	}

}
